const Model = require('../models/userModel')
const menuModel = require('../models/menuModel')

const getAllUsers = async (ctx) => {
  try {
    ctx.body = { success: true, data: await Model.getUserByUserAll() }
    console.log('ctx.body set to:', ctx.body)
  } catch (error) {
    console.error('Error setting ctx.body:', error)
    ctx.status = 500
    ctx.body = { success: false, message: 'Internal Server Error' }
  }
}

const save = async (ctx) => {
  const { username, email, phone, nickname, role, role_id } = ctx.request.body
  await Model.createUser(username, '123456', email, phone, nickname, role, role_id)
  ctx.body = { success: true }
}

const login = async (ctx) => {
  const { username, password } = ctx.request.body
  const user = await Model.login(username, password)
  let success = false
  let menus = []
  if (user) {
    success = true
    menus = await menuModel.findByRoleId(user.role_id)
  }
  ctx.body = { success, data: { user, menus } }
}

const update = async (ctx) => {
  const { username, email, phone, nickname, role, role_id, id } = ctx.request.body
  await Model.update(username, email, phone, nickname, role, role_id, id)
  ctx.body = { success: true }
}
const updatePassword = async (ctx) => {
  // console.log('updatePassword:', ctx.request.body)
  // const { username, email, phone, nickname, role, role_id, id } = ctx.request.body
  ctx.body = await Model.updatePassword({ ...ctx.request.body })
}
const resetPassword = async (ctx) => {
  const { id } = ctx.request.body
  const res = await Model.resetPassword(id)
  ctx.body = { success: true }
}

const testBcrypt = async (ctx) => {
  await Model.testBcrypt()
  ctx.body = { success: true }
}
module.exports = {
  getAllUsers,
  save,
  update,
  login,
  testBcrypt,
  resetPassword,
  updatePassword,
}
